import json
import uuid
import grpc
from requests import RequestException
import inspect
import hprose
import unittest
import sys
import os
import time

# 添加执行环境
file_exec_path = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
sys.path.insert(0, file_exec_path)

from framework_strategy.gopy.trader.engine import EmailEngine, MainEngine, EventEngine  # NOQA
from framework_strategy.gopy.base.api import API, Event  # NOQA
from framework_strategy.gopy.gateways.object import *  # NOQA
from framework_strategy.gopy.gateways.xt.xt_api import XTGateway  # NOQA
from framework_strategy.gopy.gateways.object import *  # NOQA
from framework_strategy.gopy.gateways.binance.binance_api import BINANCEGateway  # NOQA
from framework_strategy.gopy.gateways.hprose import HproseClient  # NOQA
from framework_strategy.gopy.gateways.proto import message_proto_pb2, message_proto_pb2_grpc  # NOQA


option = [('grpc.keepalive_timeout_ms', 10000)]
target = "127.0.0.1:9898"
timeout = 10


def client(param: "Param"):
    """ 
    ::param data -> request-params
    """

    with grpc.insecure_channel(target=target, options=option) as channel:
        # Client
        stub = message_proto_pb2_grpc.EchoProtoServerStub(channel)
        # Invoke
        response = stub.request(message_proto_pb2.GateWayRequest(
            data=param.data, method=param.method), timeout=timeout)
        print("[client] ", response.data)


class Param:
    data: str
    method: str


class RPCProxy:

    option = [('grpc.keepalive_timeout_ms', 10000)]
    target = "127.0.0.1:9898"
    timeout = 10

    def __init__(self, client=None) -> None:
        """ """

        if not client:
            client = grpc.insecure_channel(
                target=self.target, options=self.option)
        self.client = client

    def __getattr__(self, name):
        """ """
        def do_rpc(kw=None):
            return self.do_request(name, kw)
        return do_rpc

    def do_request(self, method, kw):
        """ """
        with self.client as channel:
            # Client
            stub = message_proto_pb2_grpc.EchoProtoServerStub(channel)
            # Invoke
            if kw:
                response = stub.request(message_proto_pb2.GateWayRequest(
                    data=kw, method=method), timeout=timeout)
            else:
                response = stub.request(message_proto_pb2.GateWayRequest(
                    method=method), timeout=timeout)
            print("[client] ", response.data)


class RPCTest(unittest.TestCase):

    @unittest.skip
    def test_init(self):

        Param.data = json.dumps({"XT": {}})
        # Param.data = None
        Param.method = "get_account_info"
        client(Param)

    def test_rpc(self):

        rpc_client = RPCProxy()
        res = rpc_client.describe()
        print(res)


if __name__ == "__main__":
    unittest.main()
